import { Request, Response, NextFunction } from 'express';
import { UserRole, RoleDisplayNames } from '../consts/role';
import {hasPermission} from '../helps/role'

// 角色权限验证中间件
export const requireRole = (requiredRole: UserRole) => {
  return (req: Request, res: Response, next: NextFunction): void => {
    // 这里应该从JWT token中获取用户信息
    // 现在使用模拟数据
    const userRole = req.user?.role || UserRole.USER;

    if (userRole !== requiredRole) {
      res.status(403).json({
        success: false,
        message: `访问被拒绝：需要 ${RoleDisplayNames[requiredRole]} 权限`,
        currentRole: RoleDisplayNames[userRole],
        requiredRole: RoleDisplayNames[requiredRole]
      });
      return;
    }

    next();
  };
};

// 权限验证中间件
export const requirePermission = (permission: string) => {
  return (req: Request, res: Response, next: NextFunction): void => {
    // 这里应该从JWT token中获取用户信息
    // 现在使用模拟数据
    const userRole = req.user?.role || UserRole.USER;

    if (!hasPermission(userRole, permission)) {
      res.status(403).json({
        success: false,
        message: `访问被拒绝：缺少权限 ${permission}`,
        userRole: RoleDisplayNames[userRole]
      });
      return;
    }

    next();
  };
};

// 管理员权限验证
export const requireAdmin = requireRole(UserRole.ADMIN);

// 用户权限验证（管理员或普通用户）
export const requireUser = (req: Request, res: Response, next: NextFunction): void => {
  const userRole = req.user?.role;
  
  if (!userRole || ![UserRole.ADMIN, UserRole.USER].includes(userRole)) {
    res.status(403).json({
      success: false,
      message: '访问被拒绝：需要有效的用户权限'
    });
    return;
  }

  next();
};
